<?php

/* 品牌 cate */
class Company_managerModel extends BaseModel
{
    var $table  = 'company_manager';
    var $prikey = 'cmid';
    var $_name  = 'company_manager';
	
    var $_relation = array(
		'has_member' => array(
            'model'         => 'member',
            'type'          => HAS_ONE,
            'foreign_key'   => 'user_id',
            'refer_key'   => 'uid',
        ),
		'has_company' => array(
            'model'         => 'company',
            'type'          => HAS_ONE,
            'foreign_key'   => 'company_id',
            'refer_key'   => 'company_id',
        ),
	);

    /*
     * 获取公司对应的主管列表
	 * 参数1:公司ID,int类型
     */
    function getManagerList($company_id)
    {
		$manager_list=array();
        if(empty($company_id)){return $manager_list;}
		
		$mod_member=&m("member");
		$user_list=$this->find(array(
		'conditions' =>"company_manager.company_id={$company_id} AND role=". USER_MERCHANDISER_ADMIN,
		'join'=>"has_member"
		));
		
		foreach($user_list as $item)
		{
			$manager_list[$item['user_id']]=$item['user_name'];
		}
        return $manager_list;
    }
	
	 /*
     * 获取主管对应的品牌ID列表
	 * 参数1:主管ID,int类型
     */
    function getBrandIdList($uid)
    {
		$brand_list=array();
        if(empty($uid)){return $brand_list;}
		
		$mod_brand=&m("brand");
		$brand_list=$this->find(array(
		'conditions' =>"company_manager.company_id={$company_id} AND role=". USER_MERCHANDISER_ADMIN,
		'join'=>"has_member"
		));
		
		foreach($user_list as $item)
		{
			$manager_list[$item['user_id']]=$item['user_name'];
		}
        return $manager_list;
    }
	
	 /*
     * 保存公司对应主管关系数据
	 * 参数1:公司ID,int类型
	 * 参数2:主管用户ID,array数组类型
     */
	function saveData($company_id,$uids)
	{
		if(!is_array($uids))
		{
			return false;
		}
		$uids_tmp=array();
		foreach($uids as $item)
		{
			$uids_tmp[$item]=$item;
		}
		$uids=$uids_tmp;
		
		$data=array();
		//删除未选择的主管数据
		$this->drop("company_id={$company_id} AND uid not ".db_create_in($uids));
		
		//获取已存在数据库的数据
		$select_uid_list=$this->find(array(
		'conditions' =>"company_id={$company_id} AND uid".db_create_in($uids)
		));

		foreach($select_uid_list as $item)
		{
			if(isset($uids[$item['uid']]))
			{
				unset($uids[$item['uid']]);
			}
		}
		
		//如果无需保存返回成功
		if(empty($uids))
		{
			return true;
		}
		else
		{
		  foreach($uids as $item)
		  {
			  $data[]=array("company_id"=>$company_id,"uid"=>$item);	
		  }
		  return $this->add($data);
		}
	}
}

?>